"""
批量编辑任务对话框
"""
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QPushButton,
                           QLineEdit, QLabel, QMessageBox, QFrame, QComboBox,
                           QStackedWidget)
from PyQt6.QtCore import Qt

class TaskBatchEditDialog(QDialog):
    """批量编辑对话框"""
    
    def __init__(self, task_ids, task_manager, parent=None):
        super().__init__(parent)
        self.task_ids = task_ids
        self.task_manager = task_manager
        self.setup_ui()
        
    def setup_ui(self):
        """初始化UI"""
        self.setWindowTitle("批量编辑任务")
        self.setMinimumWidth(400)
        
        layout = QVBoxLayout(self)
        layout.setSpacing(20)
        
        # 修改类型选择
        type_group = QFrame()
        type_group.setStyleSheet("QFrame { border: 1px solid #d9d9d9; border-radius: 4px; padding: 10px; }")
        type_layout = QVBoxLayout(type_group)
        
        type_label = QLabel("修改类型")
        type_label.setStyleSheet("font-weight: bold;")
        self.type_combo = QComboBox()
        self.type_combo.addItem("修改标签", "tags")
        self.type_combo.addItem("修改买入数量", "buy_num")
        self.type_combo.addItem("修改状态", "status")
        self.type_combo.currentIndexChanged.connect(self.on_type_changed)
        
        type_layout.addWidget(type_label)
        type_layout.addWidget(self.type_combo)
        
        # 创建堆叠式窗口部件用于切换不同的输入界面
        self.input_stack = QStackedWidget()
        
        # 标签输入界面
        tags_widget = QFrame()
        tags_layout = QVBoxLayout(tags_widget)
        self.tags_input = QLineEdit()
        self.tags_input.setPlaceholderText("输入标签，多个标签用逗号分隔")
        tags_layout.addWidget(self.tags_input)
        self.input_stack.addWidget(tags_widget)
        
        # 买入数量输入界面
        buy_num_widget = QFrame()
        buy_num_layout = QVBoxLayout(buy_num_widget)
        self.buy_num_input = QLineEdit()
        self.buy_num_input.setPlaceholderText("输入买入数量")
        buy_num_layout.addWidget(self.buy_num_input)
        self.input_stack.addWidget(buy_num_widget)
        
        # 状态选择界面
        status_widget = QFrame()
        status_layout = QVBoxLayout(status_widget)
        self.status_combo = QComboBox()
        self.status_combo.addItem("启用", 1)
        self.status_combo.addItem("停用", 0)
        status_layout.addWidget(self.status_combo)
        self.input_stack.addWidget(status_widget)
        
        # 添加所有组件到主布局
        layout.addWidget(type_group)
        layout.addWidget(self.input_stack)
        
        # 按钮
        btn_layout = QHBoxLayout()
        btn_layout.setSpacing(10)
        
        cancel_btn = QPushButton("取消")
        cancel_btn.setStyleSheet("""
            QPushButton {
                background-color: white;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                padding: 5px 15px;
                font-size: 14px;
            }
            QPushButton:hover {
                border-color: #40a9ff;
                color: #40a9ff;
            }
        """)
        cancel_btn.clicked.connect(self.reject)
        
        update_btn = QPushButton("更新")
        update_btn.setStyleSheet("""
            QPushButton {
                background-color: #1890ff;
                border: none;
                border-radius: 4px;
                color: white;
                padding: 5px 15px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #40a9ff;
            }
            QPushButton:pressed {
                background-color: #096dd9;
            }
        """)
        update_btn.clicked.connect(self.accept)
        
        btn_layout.addStretch()
        btn_layout.addWidget(cancel_btn)
        btn_layout.addWidget(update_btn)
        
        layout.addLayout(btn_layout)
        
    def on_type_changed(self, index):
        """修改类型改变时的处理"""
        self.input_stack.setCurrentIndex(index)
        
    def accept(self):
        """点击更新按钮时的处理"""
        # 获取当前选择的修改类型
        current_type = self.type_combo.currentData()
        
        # 准备更新数据
        update_data = {}
        
        if current_type == "tags":
            tags_text = self.tags_input.text().strip()
            if not tags_text:
                QMessageBox.warning(self, "错误", "请输入标签")
                return
            tags = [tag.strip() for tag in tags_text.split(",") if tag.strip()]
            update_data['tags'] = tags
            
        elif current_type == "buy_num":
            buy_num_text = self.buy_num_input.text().strip()
            if not buy_num_text:
                QMessageBox.warning(self, "错误", "请输入买入数量")
                return
            if not buy_num_text.isdigit():
                QMessageBox.warning(self, "错误", "买入数量必须是数字")
                return
            update_data['buy_num_limit'] = int(buy_num_text)
            
        elif current_type == "status":
            update_data['status'] = self.status_combo.currentData()
            
        # 执行批量更新
        error_count = 0
        for task_id in self.task_ids:
            try:
                # 根据更新数据类型调用 update_task
                if current_type == "tags":
                    success = self.task_manager.update_task(task_id, tags=update_data['tags'])
                elif current_type == "buy_num":
                    success = self.task_manager.update_task(task_id, buy_num_limit=update_data['buy_num_limit'])
                elif current_type == "status":
                    success = self.task_manager.update_task(task_id, status=update_data['status'])
                
                if not success:
                    error_count += 1
                    print(f"更新任务 {task_id} 失败")
            except Exception as e:
                print(f"更新任务 {task_id} 失败: {str(e)}")
                error_count += 1
                
        if error_count > 0:
            QMessageBox.warning(self, "更新结果", f"有 {error_count} 个任务更新失败，请查看日志了解详情")
        else:
            QMessageBox.information(self, "更新结果", "所有任务更新成功")
            
        super().accept()
